﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Data.Entity.Core.Objects;

namespace EntityFramework6
{
    class Program
    {
        static void Main(string[] args)
        {
            var context = new ClientContext();
            context.Set<Model.Client>().FirstOrDefault();
            //var result2 = context.Set<Model.Client>().ToList();
            //context.Set<Model.Rabbit>().Select(x=>new { K = !x.DemoName.StartsWith("12") }).FirstOrDefault();

            string s = "F7";
            var stop = new Stopwatch();
            stop.Start();
            for (int i = 0; i < 10; i++)
            {
                DateTime sDate = DateTime.Now;
                var query2 =
                    context
                    .Set<Model.Rabbit>()
                    //.AsNoTracking()
                    //.Where(x => /*x.DemoCode=="F3" && x.DemoName =="F5"&& */x.DemoName == s)
                    .Select(a => new 
                    {
                      RizDemoCode =  a.RizDemoCode,
                      
                    });

              query2 =  query2.Take(2);

                var result = query2.ToList();
                Console.WriteLine(string.Format("第 {0} 次，用时：{1}", (i + 1), (DateTime.Now - sDate).TotalMilliseconds / 1000.0));

                // 100w 数据量明显，清掉后内存会及时释放
                result.Clear();
                result = null;
            }

            stop.Stop();
            Console.WriteLine(string.Format("运行 10 次 100w 行单表数据，用时：{0}", stop.Elapsed));

            stop.Start();

            int count = 0;
            int repeat = 5000;
            for (int i = 0; i < repeat; i++)
            {
                var result = context
                    .Set<Model.Client>()
                    .ToList();
                count = result.Count;
            }

            stop.Stop();
            Console.WriteLine(string.Format("单表查询：{0} 笔记录重复执行 {1} 次，共耗时 {2} 毫秒（{3}）", count, repeat, stop.ElapsedMilliseconds, stop.Elapsed));
            Console.ReadLine();
            // 50s

            //<<<<<<<<<<<<<<<<<<<<<<< 分割线 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>

            context = new ClientContext();
            context.Set<Model.Client>().FirstOrDefault();
            stop = new Stopwatch();
            stop.Start();

            count = 0;
            repeat = 5000;
            for (int i = 0; i < repeat; i++)
            {
                var result = context
                    .Set<Model.Client>()
                    .Include(a => a.Accounts)
                    .ToList();
                count = result.Count;
            }

            stop.Stop();
            Console.WriteLine(string.Format("一主多从：{0} 笔记录重复执行 {1} 次，共耗时 {2} 毫秒（{3}）", count, repeat, stop.ElapsedMilliseconds, stop.Elapsed));
            Console.ReadLine();
            // 02:19s
        }
    }
}
